package com.example.datasourcedemo.controller;


import com.example.datasourcedemo.config.DataSourceManager;
import com.example.datasourcedemo.config.ResponseResult;
import com.example.datasourcedemo.pojo.DataSourceRequest;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.models.OpenAPI;
import io.swagger.v3.oas.models.Paths;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

@RestController
@Tag(name = "示例接口", description = "示例接口分类")
public class DemoController {
    @Autowired
    private DataSourceManager dataSourceManager;
    @Autowired
    private OpenAPI openAPI;



    @GetMapping("/openApi")
    @Operation(summary = "openapi", description = "表字段集合")
    public ResponseEntity<Paths> getOpenApi() {
        Paths paths = openAPI.getPaths();
        return ResponseEntity.ok(paths);
    }

    @PostMapping("/connect")
    public ResponseResult<?> connect(@RequestBody DataSourceRequest request) {
        try {
            String token = dataSourceManager.createDataSource(request);
            return ResponseResult.success(Map.of("token", token));
        } catch (Exception e) {
            return ResponseResult.fail(500, e.getMessage());
        }
    }

    @GetMapping("/databases")
    public ResponseResult<?> getDatabases(@RequestParam String token) {
        DataSourceManager.DataSourceInfo info = dataSourceManager.getDataSourceInfo(token);
        if (info == null) return ResponseResult.fail(500,"Invalid token");

        JdbcTemplate jdbcTemplate = new JdbcTemplate(info.getDataSource());
        try {
            String sql = info.getType().equalsIgnoreCase("mysql")
                    ? "SHOW DATABASES"
                    : "SELECT DISTINCT OWNER FROM ALL_OBJECTS"; // 达梦查询示例
            return ResponseResult.success(jdbcTemplate.queryForList(sql, String.class));
        } catch (Exception e) {
            return ResponseResult.fail(500,"Query error: " + e.getMessage());
        }
    }

    @PostMapping("/execute")
    public ResponseResult<?> executeSql(@RequestParam String token, @RequestBody String sql) {
        DataSourceManager.DataSourceInfo info = dataSourceManager.getDataSourceInfo(token);
        if (info == null) return ResponseResult.fail(500,"Invalid token");

        JdbcTemplate jdbcTemplate = new JdbcTemplate(info.getDataSource());
        try {
            return ResponseResult.success(jdbcTemplate.queryForList(sql));
        } catch (Exception e) {
            return ResponseResult.fail(500,"Execution error: " + e.getMessage());
        }
    }
}
